/*
 * @Author: wangtao
 * @Date: 2020-11-09 10:48:23
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-13 14:19:59
 * @Description: 上传回单
 */
import React from 'react';
import {
  Keyboard,
  NativeModules,
  ScrollView,
  StyleSheet,
  View,
} from 'react-native';
import {
  mainBgColorLightGray,
  px2dp,
} from '@/styles';
import { Button, msg } from '@/common';
import api from '@/api';
import { uploadImage } from '@/config';
import ReceiptItem from './components/receipt-item';

const { Submit } = Button;

export default class ReceiptUpload extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      wayBillData: {}, // 运单信息
      guideData: {}, // 运单引导信息
      details: [{}], // 装货、卸货相关信息
      routerFrom: '',
      id: '', // 货单Id
      keyboardHeight: 0, // 键盘高度
      unitOptionsObj: {}, // 单位对象map
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { data, routerFrom, guideData, transportNo } = params;
    this.setState({ wayBillData: data, routerFrom, guideData, transportNo });
    this.getUnitList();
    // 监听键盘
    this.keyboardDidShowListener = Keyboard.addListener(
      'keyboardWillShow',
      this._keyboardDidShow.bind(this),
    );
    this.keyboardDidHideListener = Keyboard.addListener(
      'keyboardWillHide',
      this._keyboardDidHide.bind(this),
    );
  }

  render() {
    const {
      wayBillData,
      guideData,
      details,
      keyboardHeight,
      unitOptionsObj,
    } = this.state;
    return (
      <View style={styles.container}>
        <ScrollView
          showsVerticalScrollIndicator={false}
          contentContainerStyle={{ paddingBottom: px2dp(250 + keyboardHeight) }}
        >
          <ReceiptItem
            type={wayBillData.loadingStatus === 1 ? 'loading' : 'unloading'}
            guideData={guideData}
            selectImg={this.selectImg}
            addCard={this.addCard}
            deleteCard={this.deleteCard}
            unitOptionsObj={unitOptionsObj}
            onChange={(key, val, detailsIndex) =>
              this.onChange(key, val, detailsIndex)}
            details={details}
          />
        </ScrollView>
        <Submit
          text='提交'
          boxStyle={{
            width: px2dp(640),
            height: px2dp(96),
            overflow: 'hidden',
            position: 'absolute',
            bottom: px2dp(100),
            borderRadius: px2dp(48)
          }}
          btnStyle={{}}
          btnTextStyle={{
            fontSize: px2dp(36),
          }}
          onClick={() => {
            this.submit();
          }}
        />
      </View>
    );
  }

  // 提交数据api //上传发货单，收货单
  submit = () => {
    const {
      wayBillData,
      details,
      routerFrom,
      guideData,
      transportNo,
    } = this.state;
    // 校验
    const whetherInPut = () => {
      const { weightUnit, isWeighing } = guideData;
      if (weightUnit == 'ton' || weightUnit == 'kg') {
        // 判断isWeighing字段是否存在(以前的订单没有这个字段)
        // 不存在：按之前的业务逻辑单位为ton或者kg则填写 否则不填
        // 存在：1 需要过磅 2 不需过磅； 需要过磅则填写 不需要过磅判断单位 ton或者kg则填写 否则不填
        if (!isWeighing) {
          return true;
        } if (isWeighing == 1) {
          return true;
        } if (isWeighing == 2) {
          return false;
        }
      }
      return false;
    };

    // 当满足其中单位时候填写或展示
    let weightList = ['ton', 'kg', 'piece', 'square'];

    // 单位翻译
    let weightUnitText = {
      ton: '净重',
      kg: '净重',
      piece: '件数',
      square: '方数',
    };

    if (details && details.length > 0) {
      for (let index = 0; index < details.length; index++) {
        const { fileUrl, roughWeight, tarWeight, netWeight } = details[index];

        if (!fileUrl) {
          // 是否上传了图片
          msg.emit('app:tip', { text: `第${index + 1}单票据必传` });
          return;
        }

        if (whetherInPut() && !roughWeight) {
          msg.emit('app:tip', { text: `第${index + 1}单毛重必传` });
          return;
        }

        if (whetherInPut() && !tarWeight) {
          msg.emit('app:tip', { text: `第${index + 1}单皮重必传` });
          return;
        }

        if (
          weightList.includes(guideData.weightUnit) &&
          !whetherInPut() &&
          !netWeight
        ) {
          msg.emit('app:tip', {
            text: `第${index + 1}单${weightUnitText[guideData.weightUnit]}必传`,
          });
          return;
        }
      }
    }

    api.supply
      .uploadTick({
        id: guideData.id,
        transportNo,
        details,
      })
      .then((res) => {
        if (res.success) {
          msg.emit('app:tip', { text: '提交成功' });
          msg.emit('router: refreshRoute', {
            routeName: 'DriverTab',
          });
          msg.emit('router: refreshRoute', {
            routeName: routerFrom,
          });
          msg.emit('router: goToNext', { routeName: routerFrom });
        } else {
          msg.emit('app:tip', { text: res.msg });
        }
      });
  };

    // 获取单位
    getUnitList = () => {
      api.supply.unitList().then((res) => {
        let unitOptionsObj = {};
        res.data.forEach((item) => {
          unitOptionsObj[item.code] = item.name;
        });
        this.setState({ unitOptionsObj });
      });
    };

  // 选择照片
  selectImg = (type, detailsIndex) => {
    NativeModules.DataModule.chooseImage((path, imageBase64) => {
      this.upload(path, type, detailsIndex);
    });
  };

  // 上传照片
  upload(path, type, detailsIndex) {
    NativeModules.WindowModule.showLoading();

    uploadImage('upload?dirName=carWl', path)
      .then((res) => {
        console.log('🚀🚀🚀wimi======>>>res', res);
        // 请求成功
        if (res.success) {
          this.onChange(type, res.data.localId, detailsIndex);
        } else {
          NativeModules.WindowModule.showWindow(
            { content: '上传失败，请重试', onlyRightBtn: '1' },
            (e) => {},
          );
        }
        NativeModules.WindowModule.dismissLoading();
      })
      .catch((err) => {
        NativeModules.WindowModule.dismissLoading();
        // 请求失败
        NativeModules.WindowModule.showWindow(
          { content: '上传出错，请重试', onlyRightBtn: '1' },
          (e) => {},
        );
      });
  }

  // onChange
  onChange = (key, val, detailsIndex) => {
    let { details, guideData } = this.state;
    details[detailsIndex][key] = val;
    details[detailsIndex].weightUnit = guideData.weightUnit;
    this.setState({ details });
  };

  // 新增卡片
  addCard = () => {
    let { details } = this.state;
    if (details.length >= 10) {
      msg.emit('app:tip', { text: '最多上传10张回单' });
      return;
    }
    details.push({});
    this.setState({ details });
  };

  // 删除卡片
  deleteCard = (detailsIndex) => {
    let { details } = this.state;
    details.splice(detailsIndex, 1);
    this.setState({ details });
  };

  _keyboardDidShow(e) {
    this.setState({
      keyboardHeight: e.startCoordinates.height,
    });
  }

  _keyboardDidHide(e) {
    this.setState({
      keyboardHeight: 0,
    });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    alignItems: 'center',
  },
});
